package com.fengchao.util.common;

import com.fengchao.util.common.Sms.CCPRestSmsSDK;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Random;

/**
 * Created by wangnian on 2016/6/15.
 */
@Component
public class SmsTools {

    @Autowired
    private Environment env;

    private static Logger logger = LoggerFactory.getLogger(SmsTools.class);

    public boolean sendSms(String phone, String templateId, String captcha, String minute) {
        HashMap<String, Object> result = new HashMap();
        //初始化SDK
        CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
        restAPI.init(env.getProperty("sms.location"), env.getProperty("sms.port"));
        //参数顺序：第一个参数是ACCOUNT SID，第二个参数是AUTH TOKEN
        restAPI.setAccount(env.getProperty("sms.accountsid"), env.getProperty("sms.authtoken"));
        //APPID
        restAPI.setAppId(env.getProperty("sms.appid"));
        //手机号  模板id 验证码 几分钟
        result = restAPI.sendTemplateSMS(phone, templateId, new String[]{captcha, minute});
        System.out.println("SDKTestGetSubAccounts result=" + result);
        logger.info("调用短信API响应参数 result:{}", result);
        if ("000000".equals(result.get("statusCode"))) {
            return true;
        } else {
            //异常返回输出错误码和错误信息
            logger.warn("调用短信API错误 result:{}", result);
            return false;
        }
    }

    /**
     * 随机生成4位数
     * @return
     */
    public String createCaptcha(){
        int max=9999;
        int min=1000;
        Random random = new Random();
        Integer s = random.nextInt(max)%(max-min+1) + min;
        return s.toString();
    }


}
